package com.wc.alorithm_blue_bridge._模拟.Q3399;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.ArrayList;

/**
 * @Author congge
 * @Date 2023/11/8 16:34
 * @description 小蓝的操作
 * https://www.lanqiao.cn/problems/3399/learning/?page=1&first_category_id=1&sort=students_count&tags=%E5%B7%AE%E5%88%86
 */
public class Main {
    static int max = 100000;

    public static void main(String[] args) {
        Input sc = new Input();
        int n = sc.nextInt();
        int[] array = new int[n];
        int ans = 0;
        for (int i = 0; i < n; i++) {
            array[i] = sc.nextInt();
        }
        Main main = new Main();

        int l = 0;
        int r = 0;
        while (r < n) {
            while (l < n && array[l] == 0) {
                l++;
            }
            if (l == n) {
                break;
            }
            r = l;
            while (r < n && array[r] != 0) {
                r++;
            }
            r--;
            ans += main.difference(l, r, array);
            r++;
            l = r;
        }
        System.out.println(ans - 1);
    }

    public int difference(int l, int r, int[] array) {
        if (l > r || r == array.length) {
            return 0;
        }
        if (l == r) {
            int ans = array[l];
            array[l] = 0;
            return ans;
        }
        int minIdx = l;
        ArrayList<Integer> minIdxes = new ArrayList<>();
        minIdxes.add(l);
        for (int i = l + 1; i <= r; i++) {
            if (array[minIdx] > array[i]) {
                minIdxes.clear();
                minIdxes.add(i);
                minIdx = i;
            } else if (array[minIdx] == array[i]) {
                minIdxes.add(i);
            }
        }
        int ans = array[minIdx];
        if (ans < 0) {
            System.out.println(array[minIdx]);
        }
        for (int i = l; i <= r; i++) {
            array[i] -= ans;
        }

        int size = minIdxes.size();
        ans += difference(l, minIdx - 1, array);
        for (int i = 1; i < size; i++) {
            ans += difference(minIdxes.get(i - 1) + 1, minIdxes.get(i) - 1, array);
        }
        ans += difference(minIdxes.get(size - 1) + 1, r, array);
        return ans;
    }

    static class Input {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

        public int nextInt() {
            try {
                in.nextToken();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (int) in.nval;
        }
    }
}
